<template>
    <div>
        <Row :gutter="10">
            <Col>
                <Card>
                    <Row :gutter="10">

                        <div style="float:left;margin-bottom: 10px;">
                            <Input v-model="filter.name" @on-search="search" search enter-button="查询" placeholder="请输入商品名称"
                                   style="width:250px; margin-right: 10px;float: right;top:0;font-size: 14px;"/>
                        </div>
                        <div style="float:left;margin-bottom: 10px;">
                            <Select v-model="filter.is_new" placeholder="是否新品" style="width: 100px; margin-right: 35px;" @on-change="search">
                                <Option value="-1">全部</Option>
                                <Option value="1">是</Option>
                                <Option value="0">否</Option>
                            </Select>
                        </div>
                        <div style="float:left;margin-bottom: 10px;">
                            <Select v-model="filter.is_hot" placeholder="是否热销商品" style="width: 100px; margin-right: 35px;" @on-change="search">
                                <Option value="-1">全部</Option>
                                <Option value="1">是</Option>
                                <Option value="0">否</Option>
                            </Select>
                        </div>
                        <Button type="primary" @click="addGood" style="float:right">新增</Button>
                        <Button type="primary" @click.stop="czBatch(1)" style="width: 90px;height: 32px;font-size: 14px;">批量上架</Button>
                        <Button type="primary" @click.stop="czBatch(0)" style="width: 90px;height: 32px;font-size: 14px; margin-left:20px;">批量下架</Button>
                    </Row>
                    <Row class="margin-top-10 table_pattern">
                        <Table :loading="loading" :columns="columns" :data="list" @on-selection-change="selectionChange"></Table>
                    </Row>
                    <Row class="margin-top-10">
                        <Page :total="pagenation.totalPage" :page-size="pagenation.perPage"
                              :current="pagenation.currentPage" show-elevator show-total @on-change="change"></Page>
                    </Row>
                </Card>
            </Col>
        </Row>
        <Modal v-model="show_good" :title="title" width="900px" :mask-closable="false" class="goods_modal" :z-index='450'>
            <Form v-model="formValidate"  ref="formValidate" :label-width="80">
                <FormItem label="商品名称" prop="name">
                    <Input v-model="formValidate.name" placeholder="品类名称" style="width: 370px;"/>
                </FormItem>
                <FormItem label="商品简介" prop="sub_name">
                    <Input v-model="formValidate.sub_name" placeholder="品类简介" style="width: 370px;"/>
                </FormItem>
                <FormItem label="所属品类" prop="cate_id">
                    <Cascader :data="cate_list" v-model='cate_value' @on-change='selectCate' style="width:200px;display:inline-block; margin-right:10px" placeholder="请选择品类"></Cascader>
                </FormItem>
                <FormItem label="封面图" prop="cover">
                    <div class="clearfix live_cover">
                        <div style="float: left;margin-right: 18px;">
                            <template>
                                <div v-model="formValidate.cover" class="demo-upload-list" style="height: 100px" v-if="formValidate.cover">
                                    <img :src="formValidate.cover" style='width:100px; height:100px;object-fit: cover;'>
                                    <div class="demo-upload-list-cover">
                                        <Icon type="ios-eye-outline" @click.native="handleView(formValidate.cover)"></Icon>
                                        <Icon type="ios-trash-outline" @click.native="handleRemove(1)"></Icon>
                                    </div>
                                </div>
                                <div v-if="formValidate.cover == ''||formValidate.cover==null">
                                    <div class="no_pic">
                                        <img src="../../assets/images/expo/pic2.png" alt="" width="24"/>
                                    </div>
                                </div>
                            </template>
                        </div>
                        <Upload
                                ref="upload"
                                :max-size="5120"
                                :show-upload-list="false"
                                action="https://up.qiniup.com"
                                :on-format-error="handleFormatError"
                                :before-upload="handleBeforeUpload"
                                :on-progress="handleProgress"
                                :on-success="handleCoverSuccess"
                                :on-error="handleError"
                                :data="{token:upload_token}"
                                style="float: left;"
                        >
                            <Button style="width:80px;height:30px;background:rgba(248,249,250,1);border:1px solid rgba(232,233,237,1);border-radius:2px;">上传图片</Button>
                            <p style="color:#999;margin-top: 8px;">建议尺寸: 150*150px，JPG、PNG格式，图片小于5M</p>
                        </Upload>
                    </div>
                </FormItem>
                <FormItem label="商品轮播图">
                    <div>
                        <Row type="flex" justify="start" align="middle" class="height-100">
                            <div style="display: block;text-align: center;">
                                <Upload
                                    ref="upload"
                                    :max-size="5120"
                                    :show-upload-list="false"
                                    action="https://up.qiniup.com"
                                    :on-format-error="handleFormatError"
                                    :before-upload="handleBeforeUpload"
                                    :on-progress="handleProgress"
                                    :on-success="handleImgsSuccess"
                                    :on-error="handleError"
                                    :data="{token:upload_token}"
                                    multiple
                                >
                                    <Button icon="ios-cloud-upload-outline">上传文件</Button>
                                    <span class="padding-left-20">建议尺寸: 375*375</span>
                                </Upload>
                            </div>
                        </Row>
                        <Row class="margin-top-20">
                            <div class="" v-if="this.good_imgs.length">
                                <template>
                                    <div class="demo-upload-list" v-for="(item,index) in good_imgs">
                                        <img :src="item" style='width:120px; height:90px'>
                                        <div class="demo-upload-list-cover">
                                            <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
                                            <Icon type="ios-trash-outline" @click.native="handleRemove(2,index)"></Icon>
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </Row>
                    </div>
                </FormItem>
                <FormItem label="商品视频" prop="video">
                    <div class="clearfix live_cover">
                        <div style="float: left;margin-right: 18px;">
                            <template>
                                <div v-model="formValidate.video" class="demo-upload-list" style="height: 100px" v-if="formValidate.video">
                                    <img :src="formValidate.video+'?vframe/jpg/offset/1'" style='width:100px; height:100px;object-fit: cover;'>
                                    <div class="demo-upload-list-cover">
                                        <Icon type="ios-eye-outline" @click.native="handleView(formValidate.video+'?vframe/jpg/offset/1')"></Icon>
                                        <Icon type="ios-trash-outline" @click.native="handleRemove(3)"></Icon>
                                    </div>
                                </div>
                                <div v-if="formValidate.video == ''||formValidate.video==null">
                                    <div class="no_pic">
                                        <img src="../../assets/images/expo/pic2.png" alt="" width="24"/>
                                    </div>
                                </div>
                            </template>
                        </div>
                        <Upload
                                ref="upload"
                                :max-size="5120*20"
                                :show-upload-list="false"
                                action="https://up.qiniup.com"
                                :on-format-error="handleFormatError"
                                :before-upload="handleBeforeUpload"
                                :on-progress="handleProgress"
                                :on-success="handleVideoSuccess"
                                :on-error="handleError"
                                :data="{token:upload_token}"
                                style="float: left;"
                        >
                            <Button style="width:80px;height:30px;background:rgba(248,249,250,1);border:1px solid rgba(232,233,237,1);border-radius:2px;">上传视频</Button>
                        </Upload>
                    </div>
                </FormItem>
                <FormItem label="商品价格" prop="price">
                    <Input v-model="formValidate.price" placeholder="商品价格" style="width: 370px;"/>
                </FormItem>
                <FormItem label="商品优惠价格" prop="price_dis">
                    <Input v-model="formValidate.price_dis" placeholder="商品优惠价格" style="width: 370px;"/>
                </FormItem>
                <FormItem label="商品详情" class="label_required">
                    <UEditor v-if="!spinShow" :msg="formValidate.content" @changeMsg="changeMsg" style="width:85%;"></UEditor>
                </FormItem>
                <FormItem label="是否新品" prop="is_new">
                    <RadioGroup v-model="formValidate.is_new">
                        <Radio label="1">是</Radio>
                        <Radio label="0">否</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="热销商品" prop="is_hot">
                    <RadioGroup v-model="formValidate.is_hot">
                        <Radio label="1">是</Radio>
                        <Radio label="0">否</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="是否返现" prop="return">
                    <RadioGroup v-model="formValidate.return">
                        <Radio label="1">返现</Radio>
                        <Radio label="0">不返现</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="返现方式" prop="return_type" v-if='formValidate.return==1'>
                    <RadioGroup v-model="formValidate.return_type">
                        <Radio label="1">按比例返现</Radio>
                        <Radio label="2">返现固定金额</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="返现比例" prop="return_pre" v-if='formValidate.return==1 && formValidate.return_type==1'>
                    <Input v-model="formValidate.return_pre" placeholder="返现比例" style="width: 370px;"/><span style='margin-left:5px'>%</span>
                </FormItem>
                <FormItem label="返现金额" prop="return_money" v-if='formValidate.return==1 && formValidate.return_type==2'>
                    <Input v-model="formValidate.return_money" placeholder="返现金额" style="width: 370px;"/>
                </FormItem>
                <FormItem label="销量基数" prop="sale_base">
                    <Input v-model="formValidate.sale_base" placeholder="销量基数" style="width: 370px;"/>
                </FormItem>
                <FormItem label="商品库存" prop="store">
                    <Input v-model="formValidate.store" placeholder="商品库存" style="width: 370px;"/>
                </FormItem>
                <FormItem label="优先级" prop="sort">
                    <Input v-model="formValidate.sort" placeholder="商品优先级" style="width: 370px;"/>
                    <span style='margin-left:10px; color:#f00'>数值越大优先显示</span>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="handleSubmit()" style="width: 90px;height: 35px;border-radius: 0;font-size: 14px;">提交</Button>
                </FormItem>
            </Form>
            <Spin fix v-if="spinShow">
                <Icon type="load-d" size=30 class="demo-spin-icon-load"></Icon>
                <div>数据加载中</div>
            </Spin>
        </Modal>
        <Modal title="查看图片" v-model="visible">
            <img :src="imgName" v-if="visible" style="width: 100%">
        </Modal>
    </div>
</template>
<script>
    import config from '@/config'
    import { getQiniu,getGood,editGood,changeGood, cateListForSelect, goodDetail, goodShareImg, goodViewImg, changeStatusBatch} from '@/api/main'
    export default {
        data() {
            return {
                columns: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center',
                    },
                    {
                        key: 'name',
                        title: '商品名称',
                        align: 'center',
                        render: (h, params) => {
                            return h('strong',  params.row.name)
                        },
                    },
                    {
                        key: 'sub_name',
                        title: '商品简介',
                        align: 'center',
                        render: (h, params) => {
                            return h('strong',  params.row.sub_name)
                        },
                    },
                    {
                        key: 'cate_name',
                        title: '所属品类',
                        align: 'center',
                        render: (h, params) => {
                            return h('strong',  params.row.cate_name)
                        },
                    },
                    {
                        key: 'cover',
                        title: '封面图',
                        align: 'center',
                        render: (h, params) => {
                            return h(
                                'div',
                                {
                                    style: {
                                        backgroundImage: 'url(' + params.row.cover + ')',
                                        width: '100px',
                                        height: '60px',
                                        objectFit:'cover',
                                        margin: '10px auto',
                                        position: 'relative',
                                        cursor: 'pointer',
                                        backgroundSize: 'cover',
                                    },
                                }
                            )
                        },
                    },
                    {
                        key: 'price',
                        title: '商品价格',
                        align: 'center',
                        render: (h, params) => {
                            return h('strong',  params.row.price)
                        },
                    },
                    {
                        key: 'price_dis',
                        title: '商品优惠价格',
                        align: 'center',
                        render: (h, params) => {
                            return h('strong',  params.row.price_dis)
                        },
                    },
                    {
                        key: 'is_new',
                        title: '是否新品',
                        align: 'center',
                        render: (h, params) => {
                            return h('strong',  parseInt(params.row.is_new) ? '是' : '否')
                        },
                    },
                    {
                        key: 'is_hot',
                        title: '是否热销商品',
                        align: 'center',
                        render: (h, params) => {
                            return h('strong',  parseInt(params.row.is_hot) ? '是' : '否')
                        },
                    },
                    {
                        key: 'store',
                        title: '库存',
                        align: 'center',
                        render: (h, params) => {
                            return h('strong', params.row.store)
                        },
                    },
                    {
                        key: 'sort',
                        title: '优先级',
                        align: 'center',
                        render: (h, params) => {
                            return h('strong', params.row.sort)
                        },
                    },
                    {
                        key: 'status',
                        title: '状态',
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h(
                                    'Poptip',
                                    {
                                        props: {
                                            confirm: true,
                                            title: '确定要更改该商品状态?',
                                            transfer: true,
                                        },
                                        on: {
                                            'on-ok': () => {
                                                let obj = {}
                                                obj.id = params.row.id
                                                if(params.row.status==0){
                                                    obj.status = 1
                                                }else{
                                                    obj.status = 0
                                                }

                                                changeGood(obj).then(res => {
                                                    if (res.code === 0) {
                                                        let _this = this
                                                        this.$Message.success('更改成功')
                                                        this.init();
                                                    } else {
                                                        this.$Message.success(res.text)
                                                    }
                                                })
                                            },
                                        },
                                    },
                                    [
                                        h(
                                            'Button',
                                            {
                                                style: {
                                                    border:0,
                                                    background:'transparent',
                                                    fontSize:'14px',
                                                    color:'#377EEF'
                                                },
                                                props: {
                                                    placement: 'top',
                                                    size: 'small',
                                                },
                                            },
                                            this.getName(parseInt(params.row.status))
                                        ),
                                    ],
                                )
                            ])
                        },
                    },
                    {
                        title: '操作',
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h(
                                    'Button',
                                    {
                                        props: {
                                            size: 'small'
                                        },
                                        style: {
                                            marginRight: '5px',
                                            border:0,
                                            background:'transparent',
                                            fontSize:'14px',
                                            color:'#377EEF'
                                        },
                                        on: {
                                            click: () => {
                                                this.editGood(params.row)
                                            },
                                        },
                                    },
                                    '编辑',
                                ),
                                h(
                                    'Poptip',
                                    {
                                        props: {
                                            confirm: true,
                                            title: '您确定要删除该商品吗?',
                                            transfer: true,
                                        },
                                        on: {
                                            'on-ok': () => {
                                                let obj = {}
                                                obj.id = params.row.id
                                                obj.status = -1
                                                changeGood(obj).then(res => {
                                                    if (res.code === 0) {
                                                        let _this = this
                                                        this.$Message.success('删除成功')
                                                        let item = _this.list.find(item => {
                                                            return item.id === params.row.id
                                                        })
                                                        let index = _this.list.indexOf(item)
                                                        _this.list.splice(index,1)
                                                    } else {
                                                        this.$Message.success(res.text)
                                                    }
                                                })
                                            },
                                        },
                                    },
                                    [
                                        h(
                                            'Button',
                                            {
                                                style: {
                                                    border:0,
                                                    background:'transparent',
                                                    fontSize:'14px',
                                                    color:'#377EEF'
                                                },
                                                props: {
                                                    placement: 'top',
                                                    size: 'small',
                                                },
                                            },
                                            '删除',
                                        ),
                                    ],
                                ),
                                h(
                                  'Button',
                                  {
                                      props: {
                                          type: 'primary',
                                          size: 'small',
                                      },
                                      style: {
                                          marginRight: '5px',
                                          border:0,
                                          background:'transparent',
                                          fontSize:'14px',
                                          color:'#377EEF',
                                      },
                                      on: {
                                          click: () => {
                                            this.goodSpecsList(params.row)
                                          },
                                      },
                                  },
                                  '商品规格',
                              ),
                              h(
                                  'Button',
                                  {
                                      props: {
                                          type: 'primary',
                                          size: 'small',
                                      },
                                      style: {
                                          marginRight: '5px',
                                          border:0,
                                          background:'transparent',
                                          fontSize:'14px',
                                          color:'#377EEF',
                                      },
                                      on: {
                                          click: () => {
                                            this.goodColorList(params.row)
                                          },
                                      },
                                  },
                                  '商品颜色',
                              ),
                            ])
                        },
                    },
                ],
                spinShow: true,
                pagenation: {},
                show_good: false,
                title: '新增商品',
                list: [],
                loading: true,
                saving: false,
                upload_token: '',
                qiniu_url: '',
                visible: false,
                formValidate: {
                    name: '',
                    sub_name: '',
                    cate_id: 0,
                    cover:'',
                    imgs: '',
                    video: '',
                    content: '',
                    price: '',
                    price_dis: '',
                    return: '0',
                    return_type: '1',
                    return_pre: '',
                    return_money: '',
                    sale_base: 0,
                    is_new: '-1',
                    is_hot: '-1',
                    sort: 0,
                    store: 0,
                },
                filter: {
                    page: 0,
                    name: '',
                    is_new: '-2',
                    is_hot: '-2',
                },
                good_imgs: [],
                cate_value: [],
                cate_list: [],
                select_ids: '',
            }
        },
        methods: {
            selectionChange(val) {
              let _this = this
              if (val.length) {
                _this.select_ids = ''
                for (let i=0; i<val.length; i++) {
                  let id = val[i].id
                  _this.select_ids += id + ','
                }
                _this.select_ids = _this.select_ids.slice(0, _this.select_ids.length-1)
              }
            },
            czBatch(status) {
              let _this = this
              if (_this.select_ids == '') {
                this.$Message.error('至少选择一个商品');return;
              }
              let obj = {}
              obj.status = status
              obj.ids = _this.select_ids
              changeStatusBatch(obj).then(res => {
                if (res.code == 0) {
                  _this.$Message.success('操作成功')
                  _this.init()
                } else {
                  _this.$Message.error('操作失败')
                }
              })
            },
            goodSpecsList(obj) {
              this.$router.push({name:'good_specs',params:{id:obj.id}})
            },
            goodColorList(obj) {
              this.$router.push({name:'good_color',params:{id:obj.id}})
            },
            selectCate(value){
                this.formValidate.cate_id = value[1]
            },
            getName(status) {
              if (status == -1) {
                return '已删除'
              } else if (status == 1) {
                return '正常'
              } else if (status == 0) {
                return '下架'
              }
            },
            changeMsg (msg) {
                this.formValidate.content = msg
            },
            editGood(obj) {
                let _this = this
                this.title = '编辑商品'
                let obj_good = {}
                obj_good.id = obj.id
                goodDetail(obj_good).then(res => {
                    if (res.code === 0) {
                        _this.spinShow = true
                        _this.item_id = res.data.id
                        _this.formValidate = Object.assign({}, res.data)
                        _this.formValidate.return = res.data.return.toString()
                        _this.formValidate.return_type = res.data.return_type.toString()
                        _this.formValidate.is_new = res.data.is_new.toString()
                        _this.formValidate.is_hot = res.data.is_hot.toString()
                        _this.cate_value = []
                        _this.cate_value.push(res.data.cate_id_p, res.data.cate_id)
                        _this.good_imgs = res.data.good_imgs.split(",")
                        setTimeout(() => {
                            _this.spinShow = false
                        }, 10)
                        this.show_good = true
                        //console.log(_this.formValidate)
                    }
                })
            },
            change: function(page) {
                this.loading = true
                this.filter.page = page-1
                this.init()
            },
            search: function () {
                this.filter.page = 0
                this.init()
            },
            addGood: function () {
                this.formValidate.name = '';
                this.formValidate.sub_name = '';
                this.formValidate.cover = '';
                this.formValidate.video = '';
                this.spinShow = true
                this.formValidate.content = '';
                this.formValidate.cate_id = 0;
                this.formValidate.price = '';
                this.formValidate.price_dis = '';
                this.formValidate.imgs = '';
                this.cate_value = [];
                this.good_imgs = [];
                this.formValidate.return = '0';
                this.formValidate.return_type = '1';
                this.formValidate.return_pre = '';
                this.formValidate.return_money = '';
                this.formValidate.sale_base = 0;
                this.formValidate.is_new = '0';
                this.formValidate.is_hot = '0';
                this.formValidate.id = '';
                setTimeout(() => {
                    this.spinShow = false
                }, 1)
                this.show_good = true
            },
            handleFormatError(file) {
                this.$Message.error('文件 ' + file.name + ' 格式不正确，请选择图片文件。')
            },
            handleBeforeUpload(file) {},
            handleProgress(event, file) {},
            handleCoverSuccess(event, file, fileList) {
                this.formValidate.cover = file.response.domain+file.response.key
            },
            handleVideoSuccess(event, file, fileList) {
                this.formValidate.video = file.response.domain+file.response.key
                //console.log(this.formValidate)
            },
            handleImgsSuccess(event, file, fileList) {
                this.good_imgs.push(file.response.domain+file.response.key)
            },
            handleError(event, file) {},
            handleView(img_url) {
                this.imgName = img_url
                this.visible = true
            },
            handleRemove(type, index=0) {
                if (type == 1) {
                  this.formValidate.cover = '';
                }
                if (type == 2) {
                  this.good_imgs.splice(index, 1)
                }
                if (type == 3) {
                  this.formValidate.video = ''
                }
            },
            handleSubmit() {
                let _this = this
                if (_this.formValidate.name == '') {
                    _this.$Message.error('请填写商品名称');return;
                }
                if (_this.formValidate.sub_name == '') {
                    _this.$Message.error('请填写商品简介');return;
                }
                if (_this.formValidate.cover == '') {
                    _this.$Message.error('请上传商品封面图');return;
                }
                if (_this.good_imgs.length == 0) {
                    _this.$Message.error('请上传商品轮播图');return;
                }
                if (_this.formValidate.content == '') {
                    _this.$Message.error('请输入商品详情');return;
                }
                if (_this.formValidate.price == '') {
                    _this.$Message.error('请输入商品价格');return;
                }
                if (_this.formValidate.price_dis == '') {
                    _this.$Message.error('请输入商品优惠价格');return;
                }
                _this.formValidate.imgs = _this.good_imgs.join(',')
                //console.loog(_this.formValidate);return;
                editGood(_this.formValidate).then(res => {
                    if (res.code === 0) {
                        _this.createShareImg(res.data.id)
                        _this.createViewImg(res.data.id)
                        _this.$Message.success('操作成功')
                        _this.show_good = false
                        _this.init()
                    } else {
                        this.$Message.error(res.text)
                    }
                })
            },
            createShareImg(id) {
              let obj = {}
              obj.id = id
              goodShareImg(obj).then(res => {

              })
            },
            createViewImg(id) {
              let obj = {}
              obj.id = id
              goodViewImg(obj).then(res => {

              })
            },
            async init () {
                let qiniu = await getQiniu();
                this.upload_token = qiniu.token
                this.qiniu_url = qiniu.url
                getGood(this.filter).then(res => {
                    if (res.code == 0) {
                        this.list = res.data
                        this.loading = false
                        this.pagenation.currentPage = parseInt(res.currentPage) + 1
                        this.pagenation.totalPage = parseInt(res.totalPage)
                        this.pagenation.perPage = parseInt(res.perPage)
                    } else {
                        this.loading = false
                        this.$Message.error(res.text)
                    }
                })
            }
        },
        mounted() {
            cateListForSelect(this.filter).then(res => {
              this.cate_list = res.data
            })
            this.init()
        },
    }
</script>
